package com.dxyxx.framework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.customized.MyAdGallery;
import com.android.customized.MyAdGallery.MyOnItemClickListener;
import com.android.customized.QuickReturnHeaderHelper;
import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.framework.CAS.CallBack;
import com.dxyxx.pojo.Banner;
import com.dxyxx.pojo.HomePageBanner;
import com.dxyxx.pojo.TopBanner;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.example.universalimageloader.ScaleBitmapDisplayer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * 
 * UI描述： 主页。第一层是titlebar，占用50dp；
 * 
 * 第二层是 广告横幅，占用200dp；
 * 
 * 第三层的 四个 圆形选项，占用100dp；
 * 
 * 剩下空间给首页横幅列表。
 * 
 * 这里引用了 quickreturn 项目这个lib，做了一点特效。
 * 
 * 
 * @author chinesejie@qq.com
 * 
 */
public class HomepageFragment extends BaseFragment {
	// protected ImageLoader imageLoader = ImageLoader.getInstance();
	String[] imageUrls;
	DisplayImageOptions options;
	private MyAdGallery gallery;
	private LinearLayout ovalLayout;
	private View view;
	private double height;
	private double width;
	private double topBannerHeight;
	private ImageView refreshImage;
	private Animation anim;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		ViewGroup rootView = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.activity_homepage, null, false);
		QuickReturnHeaderHelper helper = new QuickReturnHeaderHelper(getActivity(), R.layout.component_homepage_listview, R.layout.component_homepage_header);
		view = helper.createView();
		gallery = (MyAdGallery) view.findViewById(R.id.adgallery); // 获取Gallery组件

		ovalLayout = (LinearLayout) view.findViewById(R.id.ovalLayout);// 获取圆点容器
		view.findViewById(R.id.myOrder).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				//				startActivity(new Intent(getActivity(), PayDemoActivity.class));
				CAS call = new CAS(getActivity(), RequestCode.MyOrder, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(getActivity(), OrderListActivity.class));
					}
				});
				call.call();
			}
		});
		// 算下图片的高度
		DisplayMetrics metric = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕高度（像素）
		height = width / (640.0 / 240);
		topBannerHeight = width / (640.0 / 320);
		FrameLayout.LayoutParams fl = (android.widget.FrameLayout.LayoutParams) gallery.getLayoutParams();
		fl.height = (int) topBannerHeight;
		fl.width = (int) width;
		gallery.setLayoutParams(fl);
		rootView.addView(view);
		//改成刷新按钮
		refreshImage = (ImageView) rootView.findViewById(R.id.backImageButton);
		refreshImage.setImageResource(R.drawable.refresh_normal);
		anim = AnimationUtils.loadAnimation(getActivity(), R.anim.round_loading);
		refreshImage.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {

				callNetwork();
			}
		});
		rootView.findViewById(R.id.nextImageButton).setVisibility(View.INVISIBLE);
		TextView titleView = (TextView) rootView.findViewById(R.id.title);
		titleView.setText("大象与猩猩");
		initViews(view);

		callNetwork();

		return rootView;
	}

	private void initViews(View view) {

		LinearLayout ticket = (LinearLayout) view.findViewById(R.id.ticket);
		ticket.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CAS call = new CAS(getActivity(), RequestCode.MyTicket, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(getActivity(), TicketActivity.class));
					}
				});
				call.call();

			}
		});

		LinearLayout tuan = (LinearLayout) view.findViewById(R.id.openTuan);
		tuan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getActivity(), PublicWebView.class));
			}
		});

		LinearLayout buyTicket = (LinearLayout) view.findViewById(R.id.buyTicket);
		buyTicket.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getActivity(),  BuyTicketActivity.class));
//				CAS call = new CAS(getActivity(), RequestCode.BuyTicket, new CallBack() {
//					@Override
//					public void method() {
//						startActivity(new Intent(getActivity(),  BuyTicketActivity.class));
//					}
//				});
//				call.call();
			}
		});

	}

	private final static String ID = "id";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS = "imageIds";

	class ItemAdapter extends BaseAdapter {

		private class ViewHolder {
			public TextView text;
			public ImageView image;
		}

		@Override
		public int getCount() {
			return imageUrls.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View view = convertView;
			final ViewHolder holder;
			if (convertView == null) {
				view = getActivity().getLayoutInflater().inflate(R.layout.item_homepage_imageslist, parent, false);
				holder = new ViewHolder();
				// holder.text = (TextView) view.findViewById(R.id.text);
				holder.image = (ImageView) view.findViewById(R.id.image);
				// LinearLayout.LayoutParams ll = new
				// LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
				LayoutParams params = (LayoutParams) holder.image.getLayoutParams();
				params.height = (int) height;
				params.width = (int) width;
				holder.image.setLayoutParams(params);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			// holder.text.setText("Item " + (position + 1));
			holder.image.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(getActivity(), BuyProductActivity.class);

					// 用Bundle携带数据
					Bundle bundle = new Bundle();

					//传三个值 过去。
					bundle.putString(ID, hids[position]);
					bundle.putString("categoryId", hcategoryIds[position]);
					bundle.putString(DESCRIPTION, htitles[position]);
					bundle.putString(THUMB, hthumbs[position]);
					bundle.putString(IMAGEIDS, himages[position]);
					bundle.putString(PRICE, hprices[position]);
					bundle.putString(SPECIFICATION, hspecifications[position]);
					intent.putExtras(bundle);
					startActivityForResult(intent, RequestCode.Product);

				}
			});
			imageLoader.displayImage(imageUrls[position], holder.image, options, animateFirstListener);

			return view;
		}
	}

	/**
	 * @return A list of Strings read from the specified resource
	 */
	private ArrayList<String> loadItems(int rawResourceId) {
		try {
			ArrayList<String> countries = new ArrayList<String>();
			InputStream inputStream = getResources().openRawResource(rawResourceId);
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			String line;
			while ((line = reader.readLine()) != null) {
				countries.add(line);
			}
			reader.close();
			return countries;
		} catch (IOException e) {
			return null;
		}
	}

	private String[] htitles;
	private String[] himages;
	private String[] hspecifications;
	private String[] hprices;
	private String[] hids;
	private String[] hthumbs;
	private String[] hcategoryIds;;

	 
	 
	@SuppressLint("NewApi")
	private void callNetwork() {
		refreshImage.startAnimation(anim);
		refreshImage.setClickable(false);// 禁止重复发送。
		String urlString = "banner/get";
		HttpUtil.get(urlString, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				refreshImage.setClickable(true);
				try {

					Banner banner = getObjectMapper().readValue(new String(arg2), Banner.class);
					String[] mris = new String[banner.getTopBanners().size()];
					int i = 0;
					for (TopBanner topBanner : banner.getTopBanners()) {
						mris[i] = baseImageURL + topBanner.getImageId() + "?p=0";
						i++;
					}
					int[] imageId = new int[] { R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04 };
					// 第二和第三参数 2选1 ,参数2为 图片网络路径数组 ,参数3为图片id的数组,本地测试用 ,2个参数都有优先采用参数2
					ovalLayout.removeAllViews();
					gallery.start(getActivity(), mris, imageId, 3000, ovalLayout, R.drawable.dot_focused, R.drawable.dot_normal);

					gallery.setMyOnItemClickListener(new MyOnItemClickListener() {
						public void onItemClick(int curIndex) {
							Toast.makeText(getActivity(), "点击的图片下标为:" + curIndex, Toast.LENGTH_SHORT).show();
							// System.out.println(curIndex);
						}
					});
					int size = banner.getHomePageBanners().size();
					imageUrls = new String[size];
					htitles = new String[size];
					himages = new String[size];
					hspecifications = new String[size];
					hprices = new String[size];
					hids = new String[size];
					hthumbs = new String[size];
					hcategoryIds = new String[size];

					int j = 0;
					for (HomePageBanner homePageBanner : banner.getHomePageBanners()) {

						imageUrls[j] = baseImageURL + homePageBanner.getImageId() + "?p=0";
						hids[j] = homePageBanner.getProduct().getId() + "";
						htitles[j] = homePageBanner.getProduct().getDescription();
						himages[j] = homePageBanner.getProduct().getImageIds();
						hspecifications[j] = homePageBanner.getProduct().getSpecification();
						hprices[j] = homePageBanner.getProduct().getPrice() + "";
						hthumbs[j] = homePageBanner.getProduct().getThumbId();
						hcategoryIds[j] = homePageBanner.getProduct().getCategory().getId() + "";
						j++;
					}
					options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_long1).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).cacheInMemory(true).cacheOnDisc(true).considerExifParams(true).displayer(new ScaleBitmapDisplayer()).build();
					ListView listView = (ListView) view.findViewById(android.R.id.list);
					// ArrayList<String> items = loadItems(R.raw.nyc_sites);
					// ArrayAdapter<String> adapter = new
					// ArrayAdapter<String>(getActivity(),
					// android.R.layout.simple_list_item_1, items);
					// listView.setAdapter(adapter);
					if(Build.VERSION.SDK_INT >= 9)
					{
						// listview禁止下拉反弹
						listView.setOverScrollMode(2);
					}
//					listView = (ListView) view.findViewById(android.R.id.list);
					HeaderViewListAdapter a = null;
					// View headView =
					// getActivity().getLayoutInflater().inflate(R.layout.listheader,
					// null);
					((ListView) listView).setAdapter(new ItemAdapter());
					listView.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						}
					});

				} catch (JsonParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					refreshImage.clearAnimation();
				}

			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				refreshImage.setClickable(true);
				AgainPlayer againPlayer = new AgainPlayer(getActivity(), new com.dxyxx.dialog.AgainPlayer.CallBack() {

					@Override
					public void method() {
						callNetwork();
					}
				});
				againPlayer.call("貌似没网了！");
				//				AgainPlayer.makeCall(getActivity(), "貌似没网了");
				refreshImage.clearAnimation();
			}
		});
	}

}
